
#include "VerticesColorTriangle.h"
#include <glad/glad.h>
#include <GL/gl.h>
#include <GL/glext.h>

VerticesColorTriangle::VerticesColorTriangle()
{
    vertices = {
        // positions                    // colors
        0.5f,  -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom right
        -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom left
        0.0f,  0.5f,  0.0f, 0.0f, 0.0f, 1.0f  // top
    };

    vertexShaderSource = "#version 330 core   \n\
                        layout (location = 0) in vec3 aPos;     \n\
                        layout (location = 1) in vec3 aColor;     \n\
                        out vec3 ourColor;   \n\
                        void main()  \n\
                        {    \n\
                            gl_Position = vec4(aPos, 1.0); \n\
                            ourColor = aColor;   \n\
                        }\0";
    /*
    The image may not be exactly what you would expect, since we only supplied 3
    colors, not the huge color palette we're seeing right now. This is all the
    result of something called fragment interpolation in the fragment shader.
    When rendering a triangle the rasterization stage usually results in a lot
    more fragments than vertices originally specified. The rasterizer then
    determines the positions of each of those fragments based on where they
    reside on the triangle shape.
    */
    fragmentShaderSource = "#version 330 core \n \
                            out vec4 FragColor; \n \
                            in vec3 ourColor;     \n  \
                            void main() \n\
                            {   \n\
                                FragColor = vec4(ourColor, 1.0);    \n\
                            }\0";
}

void VerticesColorTriangle::prepareVAO()
{

    unsigned int VBO;

    glGenBuffers(1, &VBO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size(),
                 vertices.data(), GL_STATIC_DRAW);

    // 配置三角形顶点 layout (location = 0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float),
                          (void*)0);
    // 启用 配置三角形顶点
    glEnableVertexAttribArray(0);

    // 配置三角形每个顶点对应的颜色 layout (location = 1)
    // (void*)(3 * sizeof(float)) 代表偏移量为三个 float 大小
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float),
                          (void*)(3 * sizeof(float)));

    // 启用配置三角形每个顶点对应的颜色
    glEnableVertexAttribArray(1);
}

void VerticesColorTriangle::render() { glDrawArrays(GL_TRIANGLES, 0, 3); }